package com.est.dase.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

import com.est.dase.R;
import com.est.dase.TabBar;
/**
 *
 * @author Fernando Geraldes, Jaime Santos, Jorge Silva
 *
 */
public class WAYWidget extends AppWidgetProvider {

	public static String ACTION_WIDGET_UP = "StatusUp";
	public static String ACTION_WIDGET_DOWN = "StatusDown";
	static RemoteViews remoteViews;

	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
		Log.i("WAY", "onEnabled");
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		Log.i("WAY", "onUpdate");
		
		
		if(remoteViews==null)
			remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
		
		actualizar(context,Status.getInstance(context).getCurrentStatus());
		
		Intent statusUp = new Intent(context, WidgetReceiverUp.class);
		statusUp.setAction(ACTION_WIDGET_UP);
		statusUp.putExtra("msg", ACTION_WIDGET_UP);

		Intent statusDown = new Intent(context, WidgetReceiverDown.class);
		statusDown.setAction(ACTION_WIDGET_DOWN);
		statusDown.putExtra("msg", ACTION_WIDGET_DOWN);

		Intent startApp = new Intent(context, TabBar.class);
		PendingIntent downPendingIntent = PendingIntent.getBroadcast(context, 0, statusDown, 0);
		PendingIntent upPendingIntent = PendingIntent.getBroadcast(context, 0, statusUp, 0);
		PendingIntent startAppPendingIntent = PendingIntent.getActivity(context, 0, startApp, PendingIntent.FLAG_UPDATE_CURRENT );

		remoteViews.setOnClickPendingIntent(R.id.widget_btn_less, downPendingIntent);
		remoteViews.setOnClickPendingIntent(R.id.widget_btn_more, upPendingIntent);
		remoteViews.setOnClickPendingIntent(R.id.widget_image, startAppPendingIntent);

		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
	}

	public static void actualizar(Context context,String valor){
//		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
		if(remoteViews==null)
			remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
		
		remoteViews.setTextViewText(R.id.widget_textview, valor);
		ComponentName thisWidget = new ComponentName(context, WAYWidget.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		manager.updateAppWidget(thisWidget, remoteViews);
	}

}
